package com.paic.egis.cssp.common.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;

import org.apache.commons.codec.binary.Base64;

/**
 * 加签工具类
 * 
 * @author XUXIANG275
 */
public class SignUtil {

    private String privateKeyFile;

    private String publicKeyFile;
    private String keyAlias;

    private String storePass;

    private String keyPass;

    private KeyStore keyStore;

    private PrivateKey privateKey;

    private PublicKey publicKey;

    /**
     * 用默认私钥对参数串进行签名
     * 
     * @param urlparam
     * @return
     */
    public String signData(String urlparam) {

        BufferedInputStream input = null;
        try {
            // 获取默认的私钥
            input = new BufferedInputStream(SignUtil.class.getClassLoader()
                    .getResourceAsStream(privateKeyFile));
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(input, storePass.toCharArray());
            Enumeration<String> enumeration= keyStore.aliases();
            while(enumeration.hasMoreElements()){
               System.out.println(enumeration.nextElement()); ;
            }
            privateKey = (PrivateKey) keyStore.getKey(keyAlias,
                    storePass.toCharArray());
            Signature dsa = Signature.getInstance("SHA1withRSA");
            dsa.initSign(privateKey);
            dsa.update(urlparam.getBytes());
            Base64 base64Encoder = new Base64();
            return new String(base64Encoder.encode(dsa.sign()));
        } catch (GeneralSecurityException gse) {
            LoggerUtil.logError(gse);
            return null;
        } catch (FileNotFoundException fnfe) {
            LoggerUtil.logError(fnfe);
            return null;
        } catch (IOException ioe) {
            LoggerUtil.logError(ioe);
            return null;
        } catch (Exception e) {
            LoggerUtil.logError("signData", e);
            return null;
        } finally {
            try {
                if (input != null)
                    input.close();
            } catch (Exception e) {
                LoggerUtil.logError(e);
            }
        }
    }

    /**
     * 用公钥证书对参数串进行签名验证
     * 
     * @param urlparam
     * @param sigparam
     * @return
     */
    public boolean verifyData(String urlparam, String sigparam) {
        boolean verifies = false;
        InputStream in = null;
        try {
            // 获得文件(相对路径)
            in = SignUtil.class.getClassLoader().getResourceAsStream(
                    publicKeyFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            publicKey = cert.getPublicKey();
            Signature dsa = Signature.getInstance("SHA1withRSA");
            dsa.initVerify(publicKey);
            dsa.update(urlparam.getBytes("utf-8"));
            Base64 base64Decoder = new Base64();
            byte[] result = base64Decoder.decode(sigparam.getBytes());
            verifies = dsa.verify(result);
            LoggerUtil.info(Arrays.toString(result).toString());
        } catch (Exception gse) {
            LoggerUtil.logError("keystore校验签名异常!", gse);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            	LoggerUtil.logError(e);
            }
        }
        return verifies;
    }
    
    /**
     * 本地测试
     * @param urlparam
     * @param sigparam
     * @return
     */
    public boolean verifyDataTest(String urlparam, String sigparam) {
        boolean verifies = false;
        InputStream in = null;
        try {
            // 获得文件(相对路径)
            in = new FileInputStream("d:/keystore.p7b");
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            publicKey = cert.getPublicKey();
            Signature dsa = Signature.getInstance("SHA1withRSA");
            dsa.initVerify(publicKey);
            dsa.update(urlparam.getBytes("utf-8"));
            Base64 base64Decoder = new Base64();
            verifies = dsa.verify(base64Decoder.decode(sigparam.getBytes()));
        } catch (Exception gse) {
            LoggerUtil.logError(gse);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                LoggerUtil.logError(e);
            }
        }
        return verifies;
    }
    
    
    public static void main(String[] args){
    	SignUtil signUtil = new SignUtil();
        //StringReader strReader = null;
        //String publicKeyFile = "keystore.cer";
        //String DESKey = "DE76E3EC39801CEEE04400144F674217";
        //signUtil.setPublicKeyFile(publicKeyFile);
    	String urlp="10378745198945E8A029E5CA74487CC55157819BE1ADBCBE1873CF0952FAE8098F9A9F1F724CEBA72523FAC56B9D0BC41668FA2A798A41C73B0544234B92CD46C843456AAA93D70AC53801A5AA57A864857D5A904FBA55FFA034F8CDED6243E91BD99C81E93D84122C365098BFF95734122DB774D43B73E7FC38AB20568381E7CD5FFC84192B65DB0E5B51BA9D26ED9449723A319BD47D2A0FC08D99F28864DC75852C6588E073070FA5BA47C30BBA640B99EAC498528D1BABF454F2E37E6ACF2188C44496A89FD40455FD0461139A1954B9B0AA6801A36B3B8F304DE9A497BC0ABBD7A1BC053BDC806ABD37793E43688827E7C91B19BD7578F51491936EAE7468159658449FC518B463E22A6220BF8BE9653BD4DBB2FF4CB0C6690E00C932A67E4A2B783B1DAE6CA8E6859113457B7687783352646695278170259932DD3AEAA8E6859113457B76BE227424F0E3B888ABF454F2E37E6ACF35B45B438F586AFB1020EBAD7DCEBE55E8158A22A52AA24C0DAFEAA76294EA96A30C6AAEADF585B8806ABD37793E43684DAFF50CA834854C67BD66572195D6AAE437E12E041EA19B91909CE47D690E3CEDD3B0C2F62F3766A661BC011DCAAF298DAC17329A9E812376055DCE2CC9AC0AB0C6690E00C932A67E4A2B783B1DAE6C9D18ACB8699792F06365114867B63243FAF4C8532B4C163F3775B10910911816D7E8AB608D9D080B3C3C8F20B89823885292AAE9617B86619AE9E9D1D56F55C03D72DD8AE497442B69C295F19F85A928122DB774D43B73E77830C889A9699F4E2C6B538595CBF82D0D6CF75905748F1C53D668F278AF85256EB854DF7CB2AEDDCD5FFC84192B65DB0E5B51BA9D26ED94F4FE89BFF7B70C58918923BC2544B6D3CD5FFC84192B65DBD65C35E1D6A342D50E6866D27E81C1A191D0F6D17AB0B2B63622A32D3DDCC338D6F9B67A97CCAC097BBC4F0E1A0AA3909A1A0C76648827523A1877507D19EAAD4F1D15A5C02431F31F968AA17552FCFD049E23C311942F1CE65B2C1F286CCBF9820316F6A901D4942271C830DA2C970B4E3BCA8C30D774049A99A67B50AE40B4931154FB37596B4C482FFC7B35FC9B7F0961574D248BA7AA1A6CF62A00273A18ABF454F2E37E6ACF35DD54D40E5E7AE8ABF71C2AC84DDF7E60D1B605D6F9EA2C3BE9541726F4A1936240CD7B2B6A3195504D1F221FE5F4157A2A9DB8ABE47AEB8061C9D6BCB13B0CA3654164E6E54492C67A77925A4CF5575931C9A4101E1B2FF84E436BBD87EF0A122DB774D43B73E7B45B01B1DB285A6F2B6C1610658CEDF44501553E4A25BC6805DE329803C17F99C53801A5AA57A8645C67AA949C98525A8827E7C91B19BD75EE4570E07B534961BDA61CF534F737EE122DB774D43B73E7AC10C6D3CDFE45BA9A1A0C76648827523A1877507D19EAAD2A556055BAD79C13F84E436BBD87EF0A122DB774D43B73E7AACA5A9D18FB9B90A68D44785322E9718D56A729C6B7CC529E6441D72938EFE4C59BD453599D40D79157C7BB145778BA05DE329803C17F99C53801A5AA57A8645C67AA949C98525A8827E7C91B19BD75EE4570E07B534961BDA61CF534F737EE122DB774D43B73E739B688E179D92545234BFC5E1094C22D740689038577C374EF57EF9C287149E742B5EEE8D8ABEA7626D1B9E16A840F17DF42149A8020D68710A7656E1BF6FBB8B1DE7726347D98931D04CD22F0EA74169885DD4023E5E180E8963604FA2923DCDF7B086F1788C4212278CE2F961BC26BCB3C8C0B91C73FA06DD6513AEFE55BD9B0C6690E00C932A699FB90971586186CF4FE89BFF7B70C585CAF74ADF8C17ED38E6CC06238E72635003A7ED9D5032ADD9A1A0C76648827523A1877507D19EAAD467D6BEC0E7BE907F84E436BBD87EF0A122DB774D43B73E7AE810A2078171C7AB06F56CAECC71209243068E28CFC987805DE329803C17F99C53801A5AA57A8645C67AA949C98525A8827E7C91B19BD75EE4570E07B534961BDA61CF534F737EE122DB774D43B73E75B39F1B5C48BAEE8504D1F221FE5F4157A2A9DB8ABE47AEB8061C9D6BCB13B0C96409FD58AAAA0897CB73EF2B10F5A05A1670720FB2DD583F84E436BBD87EF0A122DB774D43B73E7AE810A2078171C7AB06F56CAECC71209243068E28CFC987805DE329803C17F99C53801A5AA57A8645C67AA949C98525A8827E7C91B19BD75EE4570E07B534961BDA61CF534F737EE122DB774D43B73E79916A1237B90F37A468AAB51C44F8FC33F4D97D822A7A6601873CF0952FAE809B66147154438F11A8CC41C51B36522DFD8CCC15A10D42D74AD587C1080623599DEC25B25EBCE46D7D019D60600CBA0FE792101316FEE727C6EB854DF7CB2AEDDCD5FFC84192B65DBD65C35E1D6A342D50E6866D27E81C1A191D0F6D17AB0B2B63622A32D3DDCC338B24B1A451A13C731D96966B32FE6A85FC0FA257A231098BB35DC4107934A95FBA1E202F131C84B4E2FF80B9B59E29A54F0721F6444D489C510A7656E1BF6FBB8A247CD12B6D4811FA5B4C76E91032E5FA7B43CD54C488E979722436B00BBE034DF7B086F1788C4212278CE2F961BC26BCB3C8C0B91C73FA06DD6513AEFE55BD9B0C6690E00C932A67E4A2B783B1DAE6C6ED3B158683BDA1BF9C3E54F18636C64A438C413F6234735857D5A904FBA55FFF7DDD0B2EA7865DEBFFB86AAF7286062BF59F434F3515FEEFF4558BE5166028D";
    	String sign="YLeemoaX+uCDN2UXIfkiHwyGCaZuGDnQlq6QLxovfYvn9Df6dcZFJvVB+aSydu1oPtcR/CHImHVvxtizFqe3iOSErWK4Z4CfLbo8yWnOfcbO0PJ2Yh3CQq4f8Zom6muZ33HYSLusFOJpnwZCibgPLleGBYemWpMCgr39WndufzI=";
    	signUtil.verifyDataTest(urlp, sign);
    	
    	
    }

    public String getPrivateKeyFile() {
        return privateKeyFile;
    }

    public void setPrivateKeyFile(String privateKeyFile) {
        this.privateKeyFile = privateKeyFile;
    }

    public String getPublicKeyFile() {
        return publicKeyFile;
    }

    public void setPublicKeyFile(String publicKeyFile) {
        this.publicKeyFile = publicKeyFile;
    }

    public String getKeyAlias() {
        return keyAlias;
    }

    public void setKeyAlias(String keyAlias) {
        this.keyAlias = keyAlias;
    }

    public String getStorePass() {
        return storePass;
    }

    public void setStorePass(String storePass) {
        this.storePass = storePass;
    }

    public String getKeyPass() {
        return keyPass;
    }

    public void setKeyPass(String keyPass) {
        this.keyPass = keyPass;
    }

    public KeyStore getKeyStore() {
        return keyStore;
    }

    public void setKeyStore(KeyStore keyStore) {
        this.keyStore = keyStore;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

}